package com.datagateway.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 启动初始化组件
 * 在应用启动时执行必要的初始化操作
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@Component
public class StartupInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(StartupInitializer.class);

    @Autowired
    private HiveWriter hiveWriter;

    @Autowired
    private GroovyScriptEngine groovyScriptEngine;

    /**
     * 应用启动时执行初始化操作
     * 
     * @param args 命令行参数
     * @throws Exception 初始化异常
     */
    @Override
    public void run(String... args) throws Exception {
        logger.info("开始执行启动初始化...");
        
        try {
            // 初始化Hive表
            initializeHiveTable();
            
            // 初始化Groovy脚本引擎
            initializeGroovyScriptEngine();
            
            logger.info("启动初始化完成");
            
        } catch (Exception e) {
            logger.error("启动初始化失败", e);
            throw e;
        }
    }

    /**
     * 初始化Hive表
     */
    private void initializeHiveTable() {
        try {
            logger.info("开始初始化Hive表...");
            hiveWriter.createTableIfNotExists();
            logger.info("Hive表初始化成功");
        } catch (Exception e) {
            logger.error("Hive表初始化失败", e);
            throw new RuntimeException("Hive表初始化失败", e);
        }
    }

    /**
     * 初始化Groovy脚本引擎
     */
    private void initializeGroovyScriptEngine() {
        try {
            logger.info("开始初始化Groovy脚本引擎...");
            
            // 获取脚本引擎状态
            var status = groovyScriptEngine.getCacheStatus();
            logger.info("Groovy脚本引擎初始化成功，缓存状态: {}", status);
            
        } catch (Exception e) {
            logger.error("Groovy脚本引擎初始化失败", e);
            throw new RuntimeException("Groovy脚本引擎初始化失败", e);
        }
    }
}
